package com.um.jdy.platform.month.manager;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.month.entity.dto.CardUserDTO;
import com.um.jdy.common.month.entity.po.CardUser;
import com.um.jdy.platform.month.entity.vo.CardUserItemVO;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.jdy.common.month.service.CardUserService;
import com.um.springboot.starter.orm.params.PageParams;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.util.Date;

/**
 * 管理类：月卡用户表
 */
@Component
public class CardUserManager extends BaseManager<CardUserService> {

    /**
     * 分页查询订单
     * @param pageParams
     * @return
     */
    public Response<Page<CardUserItemVO>> getPage(PageParams pageParams) {
        Page<CardUserItemVO> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());

        pageParams.getCondition().put("cu.com_id",getComId());

        page = service.getCMSViewModelPageBySqlName(page, "get_monthcard_user_page", "get_monthcard_user_count",
                CardUserItemVO.class, pageParams.getProperties(), pageParams.getValues(),
                pageParams.getRangeEntitys(), pageParams.getOrderNames(), pageParams.getSortOns());
        page.getResult().stream().forEach(item -> {
            Date now = new Date();
            int days = (int) DateUtil.between(DateUtil.parseDate(DateUtil.format(now,"yyyy-MM-dd")), item.getEndDate(), DateUnit.DAY);
            item.setDays(days);
            item.setIsExpired(now.compareTo( item.getEndDate()) <= 0 ? YesOrNo.No.name() : YesOrNo.Yes.name());
        });
        return Response.success(page);
    }

    public Response<CardUser> updateEntity(String id, CardUserDTO dto) {
        CardUser entity = service.getEntity(id);
        BeanUtils.copyProperties(dto, entity);
        return Response.success(this.service.updateEntity(entity));
    }

}
